import { Context, Next } from 'koa';
import { AuthService } from '../services/AuthService';

const authService = new AuthService();

/**
 * 认证中间件
 * 验证用户会话并设置用户信息到ctx.state
 */
export const authMiddleware = async (ctx: Context, next: Next) => {
  try {
    const sessionId = ctx.cookies.get('sessionId') || ctx.headers.authorization?.replace('Bearer ', '');

    if (!sessionId) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: '未提供认证信息'
      };
      return;
    }

    // 验证会话
    const verifyResult = await authService.verifySession(sessionId);

    if (!verifyResult.valid) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: verifyResult.message || '会话无效或已过期'
      };
      return;
    }

    // 设置用户信息到上下文
    ctx.state.user = verifyResult.user;
    ctx.state.session = verifyResult.session;
    ctx.state.system = verifyResult.system;

    await next();
  } catch (error) {
    console.error('认证中间件错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '认证验证失败'
    };
  }
};

/**
 * 管理员认证中间件
 * 验证管理员会话
 */
export const adminAuthMiddleware = async (ctx: Context, next: Next) => {
  try {
    const sessionId = ctx.cookies.get('adminSessionId') || ctx.headers.authorization?.replace('Bearer ', '');

    if (!sessionId) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: '未提供管理员认证信息'
      };
      return;
    }

    // 验证管理员会话
    const verifyResult = await authService.verifyAdminSession(sessionId);

    if (!verifyResult.valid) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: verifyResult.message || '管理员会话无效或已过期'
      };
      return;
    }

    // 设置管理员信息到上下文
    ctx.state.admin = verifyResult.user;
    ctx.state.session = verifyResult.session;
    ctx.state.isSuperAdmin = verifyResult.isSuperAdmin;

    await next();
  } catch (error) {
    console.error('管理员认证中间件错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '管理员认证验证失败'
    };
  }
};

/**
 * 可选认证中间件
 * 如果提供了认证信息则验证，否则继续执行
 */
export const optionalAuthMiddleware = async (ctx: Context, next: Next) => {
  try {
    const sessionId = ctx.cookies.get('sessionId') || ctx.headers.authorization?.replace('Bearer ', '');

    if (sessionId) {
      // 验证会话
      const verifyResult = await authService.verifySession(sessionId);

      if (verifyResult.valid) {
        // 设置用户信息到上下文
        ctx.state.user = verifyResult.user;
        ctx.state.session = verifyResult.session;
        ctx.state.system = verifyResult.system;
      }
    }

    await next();
  } catch (error) {
    console.error('可选认证中间件错误:', error);
    // 可选认证失败不阻止请求继续
    await next();
  }
};
